package com.app.admin.controller;

import com.app.admin.service.VideoService;
import com.app.common.utils.FileUtils;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/api/videos")
@RequiredArgsConstructor
public class VideoController {
    private final VideoService videoService;
    private final FileUtils fileUtils;

    // 初始化存储目录（项目启动时调用）
    @PostConstruct
    public void init() {
        videoService.init();
    }

    // 视频列表页面
    @GetMapping
    public String videoList(@RequestParam(required = false) Integer status, Model model) {
        model.addAttribute("videos", videoService.getVideoList(status));
        model.addAttribute("currentStatus", status);
        return "video/list";
    }

    // 上传页面
    @GetMapping("/upload")
    public String uploadPage() {
        return "video/upload";
    }

    // 处理上传
    @PostMapping("/upload")
    public String handleUpload(@RequestParam("file") MultipartFile file,
                               @RequestParam("title") String title,
                               @RequestParam("uploader") String uploader,
                               RedirectAttributes redirectAttributes) {
        try {
            if (file.isEmpty()) {
                redirectAttributes.addFlashAttribute("error", "请选择视频文件");
                return "redirect:/api/videos/upload";
            }
            videoService.uploadVideo(file, title, uploader);
            redirectAttributes.addFlashAttribute("success", "视频上传成功，等待审核");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "上传失败：" + e.getMessage());
        }
        return "redirect:/api/videos";
    }

    // 下载视频
    @GetMapping("/download/{id}")
    public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
        videoService.downloadVideo(id, response);
    }

    // 审核页面
    @GetMapping("/audit/{id}")
    public String auditPage(@PathVariable Long id, Model model) {
        model.addAttribute("video", videoService.getVideoList(null).stream()
                .filter(v -> v.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("视频不存在")));
        return "video/audit";
    }

    // 处理审核
    @PostMapping("/audit")
    public String handleAudit(@RequestParam Long id,
                              @RequestParam Integer status,
                              @RequestParam(required = false) String reason,
                              RedirectAttributes redirectAttributes) {
        try {
            videoService.auditVideo(id, status, reason);
            redirectAttributes.addFlashAttribute("success", "审核完成");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "审核失败：" + e.getMessage());
        }
        return "redirect:/api/videos?status=0"; // 回到待审核列表
    }
}
